package com.rainwood.water_authority.ui.activity;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.rainwood.water_authority.R;
import com.rainwood.water_authority.aop.SingleClick;
import com.rainwood.water_authority.base.App;
import com.rainwood.water_authority.base.MyBaseActivity;
import com.rainwood.water_authority.helper.InputTextHelper;
import com.rainwood.water_authority.http.request.LoginApi;
import com.rainwood.water_authority.http.response.LoginResultBean;
import com.rainwood.water_authority.model.CacheLoginBean;
import com.rainwood.water_authority.other.KeyboardWatcher;
import com.rainwood.water_authority.util.SecuritySharedPreference;
import com.sxs.easyhttp.EasyConfig;
import com.sxs.easyhttp.EasyHttp;
import com.sxs.easyhttp.listener.HttpCallback;

/**
 * @author sxs
 * @date :2020/9/28
 * @desc: 登录
 */
public final class LoginAty extends MyBaseActivity implements KeyboardWatcher.SoftKeyboardStateListener {

    public static void start(Context context) {
        Intent intent = new Intent(context, LoginAty.class);
        context.startActivity(intent);
    }

    private ImageView mLogoView;
    private ViewGroup mBodyLayout;
    private EditText mAccountView;
    private EditText mPasswordView;
    private View mForgetView;
    private Button mCommitView;
    private View mBlankView;

    /**
     * logo 缩放比例
     */
    private final float mLogoScale = 0.8f;
    /**
     * 动画时间
     */
    private final int mAnimTime = 300;

    private SecuritySharedPreference.SecurityEditor editor;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected void initView() {
        mLogoView = findViewById(R.id.iv_login_logo);
        mBodyLayout = findViewById(R.id.ll_login_body);
        mAccountView = findViewById(R.id.et_login_phone);
        mPasswordView = findViewById(R.id.et_login_password);
        mForgetView = findViewById(R.id.tv_login_forget);
        mCommitView = findViewById(R.id.btn_login_commit);
        mBlankView = findViewById(R.id.v_login_blank);

        setOnClickListener(mForgetView, mCommitView);

        InputTextHelper.with(this)
                .addView(mAccountView)
                .addView(mPasswordView)
                .setMain(mCommitView)
                .build();
    }

    @Override
    protected void initData() {
        editor = new SecuritySharedPreference(App.getContext(), null, MODE_PRIVATE).edit();
        postDelayed(() -> {
            // 因为在小屏幕手机上面，因为计算规则的因素会导致动画效果特别夸张，所以不在小屏幕手机上面展示这个动画效果
            if (mBlankView.getHeight() > mBodyLayout.getHeight()) {
                // 只有空白区域的高度大于登录框区域的高度才展示动画
                KeyboardWatcher.with(LoginAty.this)
                        .setListener(LoginAty.this);
            }
        }, 500);

        mAccountView.setText("yumu");
        mPasswordView.setText("123456");
    }

    @SingleClick
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_login_commit:
                EasyHttp.post(this)
                        .api(new LoginApi()
                                .setUsername(mAccountView.getText().toString().trim())
                                .setPasswd(mPasswordView.getText().toString().trim()))
                        .request(new HttpCallback<LoginResultBean>(this) {
                            @Override
                            public void onSucceed(LoginResultBean result) {
                                toast(result.getWarn());
                                if (result.getCode() == 1 && result.getData() != null) {
                                    // 设置token
                                    EasyConfig.getInstance().addHeader("Auth", result.getData().getToken());
                                    // 缓存用户名、密码
                                    CacheLoginBean cacheLoginBean = new CacheLoginBean();
                                    cacheLoginBean.setUserName(mAccountView.getText().toString().trim());
                                    cacheLoginBean.setPwd(mPasswordView.getText().toString().trim());
                                    cacheLoginBean.setToken(result.getData().getToken());

                                    editor.putBoolean("login_state", true);
                                    editor.putString("loginCache", cacheLoginBean.toString());
                                    editor.apply();
                                    startActivity(MainActivity.class);

                                    //SQLiteHelper.with(getContext()).delete(CacheLoginBean.class, null, null);
                                    //SQLiteHelper.with(getContext()).insert(cacheLoginBean);
                                }
                                // startActivity(HomeActivity.class);
                            }
                        });
                break;
            case R.id.tv_login_forget:
                toast("忘记密码");
                break;
            default:
                break;
        }
    }

    @Override
    public void onSoftKeyboardOpened(int keyboardHeight) {
        int screenHeight = getResources().getDisplayMetrics().heightPixels;
        int[] location = new int[2];
        // 获取这个 View 在屏幕中的坐标（左上角）
        mBodyLayout.getLocationOnScreen(location);
        //int x = location[0];
        int y = location[1];
        int bottom = screenHeight - (y + mBodyLayout.getHeight());
        if (keyboardHeight > bottom) {
            // 执行位移动画
            ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(mBodyLayout, "translationY", 0, -(keyboardHeight - bottom));
            objectAnimator.setDuration(mAnimTime);
            objectAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
            objectAnimator.start();

            // 执行缩小动画
            mLogoView.setPivotX(mLogoView.getWidth() / 2f);
            mLogoView.setPivotY(mLogoView.getHeight());
            AnimatorSet animatorSet = new AnimatorSet();
            ObjectAnimator scaleX = ObjectAnimator.ofFloat(mLogoView, "scaleX", 1.0f, mLogoScale);
            ObjectAnimator scaleY = ObjectAnimator.ofFloat(mLogoView, "scaleY", 1.0f, mLogoScale);
            ObjectAnimator translationY = ObjectAnimator.ofFloat(mLogoView, "translationY", 0.0f, -(keyboardHeight - bottom));
            animatorSet.play(translationY).with(scaleX).with(scaleY);
            animatorSet.setDuration(mAnimTime);
            animatorSet.start();
        }
    }

    @Override
    public void onSoftKeyboardClosed() {
        // 执行位移动画
        ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(mBodyLayout, "translationY", mBodyLayout.getTranslationY(), 0);
        objectAnimator.setDuration(mAnimTime);
        objectAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
        objectAnimator.start();

        if (mLogoView.getTranslationY() == 0) {
            return;
        }
        // 执行放大动画
        mLogoView.setPivotX(mLogoView.getWidth() / 2f);
        mLogoView.setPivotY(mLogoView.getHeight());
        AnimatorSet animatorSet = new AnimatorSet();
        ObjectAnimator scaleX = ObjectAnimator.ofFloat(mLogoView, "scaleX", mLogoScale, 1.0f);
        ObjectAnimator scaleY = ObjectAnimator.ofFloat(mLogoView, "scaleY", mLogoScale, 1.0f);
        ObjectAnimator translationY = ObjectAnimator.ofFloat(mLogoView, "translationY", mLogoView.getTranslationY(), 0);
        animatorSet.play(translationY).with(scaleX).with(scaleY);
        animatorSet.setDuration(mAnimTime);
        animatorSet.start();
    }
}
